<template>
  <div class="monitoring-page">
    <div class="page-header">
      <div class="header-content">
        <h2>实时监控仪表盘</h2>
        <p>实时监控系统状态和生命体活动</p>
      </div>
      <div class="header-actions">
        <a-space>
          <a-badge :count="unreadAlerts" :offset="[10, 0]">
            <a-button type="primary" @click="showNotificationCenter">
              <template #icon><bell-outlined /></template>
              通知中心
            </a-button>
          </a-badge>
          <a-dropdown>
            <template #overlay>
              <a-menu @click="handleExportMenuClick">
                <a-menu-item key="pdf">
                  <file-pdf-outlined />
                  导出PDF报告
                </a-menu-item>
                <a-menu-item key="excel">
                  <file-excel-outlined />
                  导出Excel数据
                </a-menu-item>
                <a-menu-item key="json">
                  <file-text-outlined />
                  导出JSON数据
                </a-menu-item>
              </a-menu>
            </template>
            <a-button>
              <template #icon><download-outlined /></template>
              数据导出
              <down-outlined />
            </a-button>
          </a-dropdown>
          <a-switch
            v-model:checked="autoRefresh"
            checked-children="自动刷新"
            un-checked-children="手动刷新"
            @change="toggleAutoRefresh"
          />
          <a-button @click="refreshData">
            <template #icon><reload-outlined /></template>
            刷新
          </a-button>
        </a-space>
      </div>
    </div>

    <!-- 系统概览仪表盘 -->
    <a-row :gutter="[16, 16]">
      <!-- 系统性能指标 -->
      <a-col :xs="24" :sm="12" :md="6">
        <a-card>
          <a-statistic
            title="系统负载"
            :value="systemMetrics.cpuUsage"
            suffix="%"
            :value-style="{ color: getMetricColor(systemMetrics.cpuUsage, 80) }"
          >
            <template #prefix>
              <dashboard-outlined />
            </template>
          </a-statistic>
          <a-progress
            :percent="systemMetrics.cpuUsage"
            size="small"
            :stroke-color="getProgressColor(systemMetrics.cpuUsage, 80)"
            style="margin-top: 8px"
          />
        </a-card>
      </a-col>

      <a-col :xs="24" :sm="12" :md="6">
        <a-card>
          <a-statistic
            title="内存使用"
            :value="systemMetrics.memoryUsage"
            suffix="%"
            :value-style="{ color: getMetricColor(systemMetrics.memoryUsage, 85) }"
          >
            <template #prefix>
              <database-outlined />
            </template>
          </a-statistic>
          <a-progress
            :percent="systemMetrics.memoryUsage"
            size="small"
            :stroke-color="getProgressColor(systemMetrics.memoryUsage, 85)"
            style="margin-top: 8px"
          />
        </a-card>
      </a-col>

      <a-col :xs="24" :sm="12" :md="6">
        <a-card>
          <a-statistic
            title="网络延迟"
            :value="systemMetrics.networkLatency"
            suffix="ms"
            :value-style="{ color: getMetricColor(systemMetrics.networkLatency, 200, true) }"
          >
            <template #prefix>
              <wifi-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>

      <a-col :xs="24" :sm="12" :md="6">
        <a-card>
          <a-statistic
            title="活跃连接"
            :value="systemMetrics.activeConnections"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix>
              <link-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 生命体状态概览 -->
    <a-row :gutter="[16, 16]" style="margin-top: 16px">
      <a-col :xs="24" :sm="12" :md="6">
        <a-card>
          <a-statistic
            title="总生命体数量"
            :value="lifeEntityMetrics.totalCount"
            :value-style="{ color: '#52c41a' }"
          >
            <template #prefix>
              <team-outlined />
            </template>
          </a-statistic>
          <div style="margin-top: 8px">
            <a-tag color="green">+{{ lifeEntityMetrics.newToday }}</a-tag>
            <span style="color: #666; font-size: 12px">今日新增</span>
          </div>
        </a-card>
      </a-col>

      <a-col :xs="24" :sm="12" :md="6">
        <a-card>
          <a-statistic
            title="活跃生命体"
            :value="lifeEntityMetrics.activeCount"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix>
              <heart-outlined />
            </template>
          </a-statistic>
          <div style="margin-top: 8px">
            <a-progress
              :percent="Math.round((lifeEntityMetrics.activeCount / lifeEntityMetrics.totalCount) * 100)"
              size="small"
              :stroke-color="'#1890ff'"
            />
          </div>
        </a-card>
      </a-col>

      <a-col :xs="24" :sm="12" :md="6">
        <a-card>
          <a-statistic
            title="平均健康度"
            :value="lifeEntityMetrics.avgHealthScore"
            suffix="/100"
            :precision="1"
            :value-style="{ color: getHealthScoreColor(lifeEntityMetrics.avgHealthScore) }"
          >
            <template #prefix>
              <medicine-box-outlined />
            </template>
          </a-statistic>
          <div style="margin-top: 8px">
            <a-badge :status="getHealthStatus(lifeEntityMetrics.avgHealthScore)" :text="getHealthText(lifeEntityMetrics.avgHealthScore)" />
          </div>
        </a-card>
      </a-col>

      <a-col :xs="24" :sm="12" :md="6">
        <a-card>
          <a-statistic
            title="网络连接数"
            :value="lifeEntityMetrics.networkConnections"
            :value-style="{ color: '#722ed1' }"
          >
            <template #prefix>
              <cluster-outlined />
            </template>
          </a-statistic>
          <div style="margin-top: 8px">
            <span style="color: #666; font-size: 12px">
              密度: {{ (lifeEntityMetrics.networkDensity * 100).toFixed(1) }}%
            </span>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 生命体活跃度和健康状态监控 -->
    <a-row :gutter="[16, 16]" style="margin-top: 16px">
      <a-col :xs="24" :lg="12">
        <a-card title="生命体活跃度监控" :bordered="false">
          <template #extra>
            <a-space>
              <a-select v-model:value="activityFilter" size="small" style="width: 120px">
                <a-select-option value="all">全部类型</a-select-option>
                <a-select-option value="corporate">企业</a-select-option>
                <a-select-option value="urban">城市</a-select-option>
                <a-select-option value="conceptual">概念</a-select-option>
                <a-select-option value="hybrid">混合</a-select-option>
              </a-select>
              <a-button size="small" @click="refreshActivityData">
                <template #icon><reload-outlined /></template>
              </a-button>
            </a-space>
          </template>
          
          <a-timeline mode="left" style="margin-top: 16px">
            <a-timeline-item
              v-for="activity in filteredActivities"
              :key="activity.id"
              :color="getActivityTimelineColor(activity.type)"
            >
              <template #dot>
                <component :is="getActivityIcon(activity.type)" />
              </template>
              <div class="activity-item">
                <div class="activity-header">
                  <span class="activity-entity">{{ activity.entityName }}</span>
                  <a-tag :color="getActivityTagColor(activity.type)" size="small">
                    {{ activity.type }}
                  </a-tag>
                </div>
                <div class="activity-description">{{ activity.description }}</div>
                <div class="activity-meta">
                  <span class="activity-time">{{ formatTime(activity.timestamp) }}</span>
                  <a-badge 
                    v-if="activity.healthScore" 
                    :status="getHealthBadgeStatus(activity.healthScore)" 
                    :text="`健康度: ${activity.healthScore}`" 
                  />
                </div>
              </div>
            </a-timeline-item>
          </a-timeline>
        </a-card>
      </a-col>

      <a-col :xs="24" :lg="12">
        <a-card title="健康状态分布" :bordered="false">
          <div class="health-distribution">
            <a-row :gutter="[8, 8]">
              <a-col :span="12">
                <div class="health-stat-item">
                  <div class="health-stat-value excellent">{{ healthDistribution.excellent }}</div>
                  <div class="health-stat-label">
                    <a-badge status="success" text="优秀" />
                  </div>
                </div>
              </a-col>
              <a-col :span="12">
                <div class="health-stat-item">
                  <div class="health-stat-value good">{{ healthDistribution.good }}</div>
                  <div class="health-stat-label">
                    <a-badge status="processing" text="良好" />
                  </div>
                </div>
              </a-col>
              <a-col :span="12">
                <div class="health-stat-item">
                  <div class="health-stat-value warning">{{ healthDistribution.warning }}</div>
                  <div class="health-stat-label">
                    <a-badge status="warning" text="警告" />
                  </div>
                </div>
              </a-col>
              <a-col :span="12">
                <div class="health-stat-item">
                  <div class="health-stat-value critical">{{ healthDistribution.critical }}</div>
                  <div class="health-stat-label">
                    <a-badge status="error" text="危险" />
                  </div>
                </div>
              </a-col>
            </a-row>
          </div>
          
          <a-divider />
          
          <div class="recent-health-changes">
            <h4>近期健康状态变化</h4>
            <a-list :data-source="recentHealthChanges" size="small">
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-list-item-meta>
                    <template #avatar>
                      <a-avatar :style="{ backgroundColor: getHealthChangeColor(item.change) }">
                        <component :is="getHealthChangeIcon(item.change)" />
                      </a-avatar>
                    </template>
                    <template #title>
                      {{ item.entityName }}
                    </template>
                    <template #description>
                      健康度从 {{ item.oldScore }} 变为 {{ item.newScore }}
                      <span style="margin-left: 8px; color: #666">
                        {{ formatTime(item.timestamp) }}
                      </span>
                    </template>
                  </a-list-item-meta>
                </a-list-item>
              </template>
            </a-list>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 告警和通知功能 -->
    <a-row :gutter="[16, 16]" style="margin-top: 16px">
      <a-col :xs="24" :lg="16">
        <a-card title="实时告警" :bordered="false">
          <template #extra>
            <a-space>
              <a-select v-model:value="alertFilter" size="small" style="width: 100px">
                <a-select-option value="all">全部</a-select-option>
                <a-select-option value="error">错误</a-select-option>
                <a-select-option value="warning">警告</a-select-option>
                <a-select-option value="info">信息</a-select-option>
              </a-select>
              <a-button size="small" @click="clearAllAlerts" :disabled="alerts.length === 0">
                清空告警
              </a-button>
            </a-space>
          </template>
          
          <div v-if="filteredAlerts.length === 0" class="empty-alerts">
            <a-empty description="暂无告警信息" />
          </div>
          
          <div v-else class="alerts-container">
            <a-alert
              v-for="alert in filteredAlerts"
              :key="alert.id"
              :type="alert.level"
              :message="alert.message"
              :description="alert.description"
              :closable="true"
              :show-icon="true"
              style="margin-bottom: 8px"
              @close="dismissAlert(alert.id)"
            >
              <template #action>
                <a-space>
                  <a-button size="small" type="link" @click="viewAlertDetails(alert)">
                    详情
                  </a-button>
                  <span style="color: #666; font-size: 12px">
                    {{ formatTime(alert.timestamp) }}
                  </span>
                </a-space>
              </template>
            </a-alert>
          </div>
        </a-card>
      </a-col>

      <a-col :xs="24" :lg="8">
        <a-card title="系统通知" :bordered="false">
          <template #extra>
            <a-badge :count="unreadNotifications">
              <a-button size="small" @click="markAllNotificationsRead">
                全部已读
              </a-button>
            </a-badge>
          </template>
          
          <a-list :data-source="notifications" size="small">
            <template #renderItem="{ item }">
              <a-list-item 
                :class="{ 'unread-notification': !item.read }"
                @click="markNotificationRead(item.id)"
              >
                <a-list-item-meta>
                  <template #avatar>
                    <a-badge :dot="!item.read">
                      <a-avatar :style="{ backgroundColor: getNotificationColor(item.type) }">
                        <component :is="getNotificationIcon(item.type)" />
                      </a-avatar>
                    </a-badge>
                  </template>
                  <template #title>
                    {{ item.title }}
                  </template>
                  <template #description>
                    {{ item.content }}
                    <div style="margin-top: 4px; color: #999; font-size: 11px">
                      {{ formatTime(item.timestamp) }}
                    </div>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-col>
    </a-row>

    <!-- 性能图表和数据导出 -->
    <a-row :gutter="[16, 16]" style="margin-top: 16px">
      <a-col :span="24">
        <a-card title="性能趋势分析" :bordered="false">
          <template #extra>
            <a-space>
              <a-range-picker
                v-model:value="dateRange"
                size="small"
                @change="onDateRangeChange"
              />
              <a-select v-model:value="chartMetric" size="small" style="width: 120px">
                <a-select-option value="health">健康度</a-select-option>
                <a-select-option value="activity">活跃度</a-select-option>
                <a-select-option value="performance">性能</a-select-option>
                <a-select-option value="network">网络</a-select-option>
              </a-select>
            </a-space>
          </template>
          
          <div ref="performanceChartRef" style="height: 300px">
            <div class="chart-placeholder">
              <div style="text-align: center; padding: 100px 0; color: #666">
                <line-chart-outlined style="font-size: 48px; margin-bottom: 16px" />
                <div>{{ chartMetric === 'health' ? '健康度' : chartMetric === 'activity' ? '活跃度' : chartMetric === 'performance' ? '性能' : '网络' }}趋势图表</div>
                <div style="font-size: 12px; margin-top: 8px">实时显示{{ getChartDescription(chartMetric) }}</div>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 数据导出和报告生成 -->
    <a-row :gutter="[16, 16]" style="margin-top: 16px">
      <a-col :span="24">
        <a-card title="数据导出和报告生成" :bordered="false">
          <a-row :gutter="[16, 16]">
            <a-col :xs="24" :md="8">
              <div class="export-section">
                <h4>
                  <file-excel-outlined style="color: #52c41a; margin-right: 8px" />
                  Excel 数据导出
                </h4>
                <p>导出监控数据到Excel文件，支持自定义时间范围和数据类型</p>
                <a-space direction="vertical" style="width: 100%">
                  <a-select v-model:value="exportDataType" style="width: 100%">
                    <a-select-option value="all">全部数据</a-select-option>
                    <a-select-option value="system">系统指标</a-select-option>
                    <a-select-option value="lifeEntity">生命体数据</a-select-option>
                    <a-select-option value="alerts">告警记录</a-select-option>
                  </a-select>
                  <a-button type="primary" block @click="exportToExcel" :loading="exportLoading.excel">
                    <template #icon><download-outlined /></template>
                    导出Excel
                  </a-button>
                </a-space>
              </div>
            </a-col>
            
            <a-col :xs="24" :md="8">
              <div class="export-section">
                <h4>
                  <file-pdf-outlined style="color: #f5222d; margin-right: 8px" />
                  PDF 报告生成
                </h4>
                <p>生成包含图表和分析的完整监控报告</p>
                <a-space direction="vertical" style="width: 100%">
                  <a-select v-model:value="reportTemplate" style="width: 100%">
                    <a-select-option value="summary">概要报告</a-select-option>
                    <a-select-option value="detailed">详细报告</a-select-option>
                    <a-select-option value="health">健康状态报告</a-select-option>
                    <a-select-option value="performance">性能分析报告</a-select-option>
                  </a-select>
                  <a-button type="primary" block @click="generatePDFReport" :loading="exportLoading.pdf">
                    <template #icon><file-pdf-outlined /></template>
                    生成PDF报告
                  </a-button>
                </a-space>
              </div>
            </a-col>
            
            <a-col :xs="24" :md="8">
              <div class="export-section">
                <h4>
                  <api-outlined style="color: #1890ff; margin-right: 8px" />
                  API 数据导出
                </h4>
                <p>通过API接口导出JSON格式的实时数据</p>
                <a-space direction="vertical" style="width: 100%">
                  <a-input-group compact>
                    <a-select v-model:value="apiFormat" style="width: 70%">
                      <a-select-option value="json">JSON格式</a-select-option>
                      <a-select-option value="csv">CSV格式</a-select-option>
                      <a-select-option value="xml">XML格式</a-select-option>
                    </a-select>
                    <a-button @click="copyApiUrl" style="width: 30%">
                      <template #icon><copy-outlined /></template>
                    </a-button>
                  </a-input-group>
                  <a-button type="primary" block @click="exportViaAPI" :loading="exportLoading.api">
                    <template #icon><cloud-download-outlined /></template>
                    API导出
                  </a-button>
                </a-space>
              </div>
            </a-col>
          </a-row>
          
          <a-divider />
          
          <div class="export-history">
            <h4>导出历史</h4>
            <a-table
              :columns="exportHistoryColumns"
              :data-source="exportHistory"
              :pagination="{ pageSize: 5, size: 'small' }"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'status'">
                  <a-tag :color="getExportStatusColor(record.status)">
                    {{ record.status }}
                  </a-tag>
                </template>
                <template v-if="column.key === 'actions'">
                  <a-space>
                    <a-button 
                      v-if="record.status === '完成'" 
                      size="small" 
                      type="link" 
                      @click="downloadExportFile(record)"
                    >
                      下载
                    </a-button>
                    <a-button size="small" type="link" @click="deleteExportRecord(record.id)">
                      删除
                    </a-button>
                  </a-space>
                </template>
                <template v-if="column.key === 'timestamp'">
                  {{ formatTime(record.timestamp) }}
                </template>
              </template>
            </a-table>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 通知中心模态框 -->
    <a-modal
      v-model:open="notificationCenterVisible"
      title="通知中心"
      width="800px"
      :footer="null"
    >
      <a-tabs v-model:activeKey="notificationTab">
        <a-tab-pane key="all" tab="全部通知">
          <notification-list :notifications="allNotifications" @read="markNotificationRead" />
        </a-tab-pane>
        <a-tab-pane key="alerts" tab="告警通知">
          <notification-list :notifications="alertNotifications" @read="markNotificationRead" />
        </a-tab-pane>
        <a-tab-pane key="system" tab="系统通知">
          <notification-list :notifications="systemNotifications" @read="markNotificationRead" />
        </a-tab-pane>
      </a-tabs>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { message, notification } from 'ant-design-vue'
import { useWebSocketStore } from '@/stores/websocket'
import type { Dayjs } from 'dayjs'
import {
  ReloadOutlined,
  DashboardOutlined,
  DatabaseOutlined,
  WifiOutlined,
  LinkOutlined,
  LineChartOutlined,
  BellOutlined,
  DownloadOutlined,
  DownOutlined,
  FilePdfOutlined,
  FileExcelOutlined,
  FileTextOutlined,
  TeamOutlined,
  HeartOutlined,
  MedicineBoxOutlined,
  ClusterOutlined,
  ApiOutlined,
  CopyOutlined,
  CloudDownloadOutlined,
  ThunderboltOutlined,
  RocketOutlined,
  BulbOutlined,
  SettingOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined,
  MinusOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons-vue'

// 组件引入
import NotificationList from '@/components/NotificationList.vue'

// 定义组件名称
defineOptions({
  name: 'MonitoringDashboard'
})

// WebSocket store
const wsStore = useWebSocketStore()

// 响应式数据
const autoRefresh = ref(true)
const refreshTimer = ref<number>()

// 系统指标
const systemMetrics = ref({
  cpuUsage: 45,
  memoryUsage: 67,
  networkLatency: 85,
  activeConnections: 234,
})

// 生命体指标
const lifeEntityMetrics = ref({
  totalCount: 1247,
  activeCount: 892,
  newToday: 23,
  avgHealthScore: 78.5,
  networkConnections: 3456,
  networkDensity: 0.67,
})

// 活动监控
const activityFilter = ref('all')
const recentActivities = ref([
  {
    id: 1,
    entityName: '智能制造公司',
    type: '状态更新',
    description: '意识等级提升到高级',
    timestamp: new Date(Date.now() - 2 * 60 * 1000),
    healthScore: 85,
    entityType: 'corporate',
  },
  {
    id: 2,
    entityName: '深圳市',
    type: '关系建立',
    description: '与广州市建立协作关系',
    timestamp: new Date(Date.now() - 5 * 60 * 1000),
    healthScore: 92,
    entityType: 'urban',
  },
  {
    id: 3,
    entityName: '创新概念',
    type: '进化',
    description: '概念结构发生变异',
    timestamp: new Date(Date.now() - 8 * 60 * 1000),
    healthScore: 76,
    entityType: 'conceptual',
  },
  {
    id: 4,
    entityName: '混合实体001',
    type: '融合',
    description: '完成多实体融合过程',
    timestamp: new Date(Date.now() - 12 * 60 * 1000),
    healthScore: 88,
    entityType: 'hybrid',
  },
])

// 健康状态分布
const healthDistribution = ref({
  excellent: 312,
  good: 567,
  warning: 289,
  critical: 79,
})

// 近期健康状态变化
const recentHealthChanges = ref([
  {
    id: 1,
    entityName: '智能制造公司',
    oldScore: 75,
    newScore: 85,
    change: 'improve',
    timestamp: new Date(Date.now() - 30 * 60 * 1000),
  },
  {
    id: 2,
    entityName: '概念实体A',
    oldScore: 82,
    newScore: 65,
    change: 'decline',
    timestamp: new Date(Date.now() - 45 * 60 * 1000),
  },
  {
    id: 3,
    entityName: '城市B',
    oldScore: 78,
    newScore: 78,
    change: 'stable',
    timestamp: new Date(Date.now() - 60 * 60 * 1000),
  },
])

// 告警和通知
const alertFilter = ref('all')
const alerts = ref([
  {
    id: 1,
    level: 'warning',
    message: 'CPU使用率持续偏高',
    description: '系统CPU使用率在过去30分钟内持续超过80%',
    timestamp: new Date(Date.now() - 10 * 60 * 1000),
  },
  {
    id: 2,
    level: 'error',
    message: '生命体连接异常',
    description: '检测到3个生命体失去网络连接',
    timestamp: new Date(Date.now() - 15 * 60 * 1000),
  },
  {
    id: 3,
    level: 'info',
    message: '新生命体创建成功',
    description: '成功创建了5个新的企业生命体',
    timestamp: new Date(Date.now() - 20 * 60 * 1000),
  },
])

const notifications = ref([
  {
    id: 1,
    type: 'system',
    title: '系统更新完成',
    content: '生命体管理系统已更新到v2.1.0',
    timestamp: new Date(Date.now() - 5 * 60 * 1000),
    read: false,
  },
  {
    id: 2,
    type: 'alert',
    title: '健康度异常',
    content: '检测到多个生命体健康度下降',
    timestamp: new Date(Date.now() - 25 * 60 * 1000),
    read: false,
  },
  {
    id: 3,
    type: 'info',
    title: '网络优化建议',
    content: '系统建议优化网络拓扑结构',
    timestamp: new Date(Date.now() - 60 * 60 * 1000),
    read: true,
  },
])

// 通知中心
const notificationCenterVisible = ref(false)
const notificationTab = ref('all')

// 数据导出
const dateRange = ref<[Dayjs, Dayjs]>()
const chartMetric = ref('health')
const exportDataType = ref('all')
const reportTemplate = ref('summary')
const apiFormat = ref('json')
const exportLoading = ref({
  excel: false,
  pdf: false,
  api: false,
})

const exportHistory = ref([
  {
    id: 1,
    type: 'Excel',
    name: '系统监控数据_20241201.xlsx',
    status: '完成',
    timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000),
  },
  {
    id: 2,
    type: 'PDF',
    name: '健康状态报告_20241201.pdf',
    status: '进行中',
    timestamp: new Date(Date.now() - 30 * 60 * 1000),
  },
])

const performanceChartRef = ref()

// 计算属性
const unreadAlerts = computed(() => alerts.value.filter(alert => !alert.dismissed).length)
const unreadNotifications = computed(() => notifications.value.filter(n => !n.read).length)

const filteredActivities = computed(() => {
  if (activityFilter.value === 'all') {
    return recentActivities.value
  }
  return recentActivities.value.filter(activity => activity.entityType === activityFilter.value)
})

const filteredAlerts = computed(() => {
  if (alertFilter.value === 'all') {
    return alerts.value
  }
  return alerts.value.filter(alert => alert.level === alertFilter.value)
})

const allNotifications = computed(() => notifications.value)
const alertNotifications = computed(() => notifications.value.filter(n => n.type === 'alert'))
const systemNotifications = computed(() => notifications.value.filter(n => n.type === 'system'))

// 表格列配置
const exportHistoryColumns = [
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: 80,
  },
  {
    title: '文件名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 80,
  },
  {
    title: '时间',
    dataIndex: 'timestamp',
    key: 'timestamp',
    width: 120,
  },
  {
    title: '操作',
    key: 'actions',
    width: 120,
  },
]

// 工具方法
const getMetricColor = (value: number, threshold: number, reverse = false) => {
  if (reverse) {
    return value > threshold ? '#cf1322' : '#3f8600'
  }
  return value > threshold ? '#cf1322' : '#3f8600'
}

const getProgressColor = (value: number, threshold: number) => {
  if (value > threshold) {
    return '#ff4d4f'
  } else if (value > threshold * 0.7) {
    return '#faad14'
  }
  return '#52c41a'
}

const getHealthScoreColor = (score: number) => {
  if (score >= 80) return '#52c41a'
  if (score >= 60) return '#1890ff'
  if (score >= 40) return '#faad14'
  return '#ff4d4f'
}

const getHealthStatus = (score: number) => {
  if (score >= 80) return 'success'
  if (score >= 60) return 'processing'
  if (score >= 40) return 'warning'
  return 'error'
}

const getHealthText = (score: number) => {
  if (score >= 80) return '优秀'
  if (score >= 60) return '良好'
  if (score >= 40) return '一般'
  return '需要关注'
}

const getActivityTimelineColor = (type: string) => {
  const colorMap = {
    '状态更新': 'blue',
    '关系建立': 'green',
    '进化': 'orange',
    '融合': 'purple',
    '交互': 'gray',
  }
  return colorMap[type as keyof typeof colorMap] || 'gray'
}

const getActivityTagColor = (type: string) => {
  const colorMap = {
    '状态更新': 'blue',
    '关系建立': 'green',
    '进化': 'orange',
    '融合': 'purple',
    '交互': 'default',
  }
  return colorMap[type as keyof typeof colorMap] || 'default'
}

const getActivityIcon = (type: string) => {
  const iconMap = {
    '状态更新': 'ThunderboltOutlined',
    '关系建立': 'LinkOutlined',
    '进化': 'RocketOutlined',
    '融合': 'ClusterOutlined',
    '交互': 'BulbOutlined',
  }
  return iconMap[type as keyof typeof iconMap] || 'SettingOutlined'
}

const getHealthBadgeStatus = (score: number) => {
  if (score >= 80) return 'success'
  if (score >= 60) return 'processing'
  if (score >= 40) return 'warning'
  return 'error'
}

const getHealthChangeColor = (change: string) => {
  const colorMap = {
    improve: '#52c41a',
    decline: '#ff4d4f',
    stable: '#1890ff',
  }
  return colorMap[change as keyof typeof colorMap] || '#666'
}

const getHealthChangeIcon = (change: string) => {
  const iconMap = {
    improve: 'ArrowUpOutlined',
    decline: 'ArrowDownOutlined',
    stable: 'MinusOutlined',
  }
  return iconMap[change as keyof typeof iconMap] || 'MinusOutlined'
}

const getNotificationColor = (type: string) => {
  const colorMap = {
    system: '#1890ff',
    alert: '#ff4d4f',
    info: '#52c41a',
  }
  return colorMap[type as keyof typeof colorMap] || '#666'
}

const getNotificationIcon = (type: string) => {
  const iconMap = {
    system: 'SettingOutlined',
    alert: 'ExclamationCircleOutlined',
    info: 'InfoCircleOutlined',
  }
  return iconMap[type as keyof typeof iconMap] || 'InfoCircleOutlined'
}

const getExportStatusColor = (status: string) => {
  const colorMap = {
    '完成': 'success',
    '进行中': 'processing',
    '失败': 'error',
  }
  return colorMap[status as keyof typeof colorMap] || 'default'
}

const getChartDescription = (metric: string) => {
  const descMap = {
    health: '生命体健康度指标变化',
    activity: '生命体活跃度指标变化',
    performance: '系统性能指标变化',
    network: '网络连接指标变化',
  }
  return descMap[metric as keyof typeof descMap] || '指标变化'
}

// 格式化时间
const formatTime = (timestamp: Date) => {
  const now = new Date()
  const diff = now.getTime() - timestamp.getTime()
  const minutes = Math.floor(diff / (1000 * 60))

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`

  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}小时前`

  const days = Math.floor(hours / 24)
  return `${days}天前`
}

// 数据刷新方法
const refreshData = () => {
  // 模拟数据更新
  systemMetrics.value = {
    cpuUsage: Math.floor(Math.random() * 100),
    memoryUsage: Math.floor(Math.random() * 100),
    networkLatency: Math.floor(Math.random() * 300),
    activeConnections: Math.floor(Math.random() * 500) + 100,
  }

  lifeEntityMetrics.value = {
    ...lifeEntityMetrics.value,
    activeCount: Math.floor(Math.random() * 100) + 800,
    avgHealthScore: Math.floor(Math.random() * 40) + 60,
  }

  message.success('数据已刷新')
}

const refreshActivityData = () => {
  // 模拟活动数据刷新
  message.success('活动数据已刷新')
}

// 自动刷新控制
const toggleAutoRefresh = (enabled: boolean) => {
  if (enabled) {
    refreshTimer.value = window.setInterval(refreshData, 30000) // 30秒刷新一次
    message.info('已开启自动刷新')
  } else {
    if (refreshTimer.value) {
      clearInterval(refreshTimer.value)
    }
    message.info('已关闭自动刷新')
  }
}

// 告警和通知方法
const showNotificationCenter = () => {
  notificationCenterVisible.value = true
}

const dismissAlert = (alertId: number) => {
  const index = alerts.value.findIndex(alert => alert.id === alertId)
  if (index > -1) {
    alerts.value[index].dismissed = true
    message.success('告警已关闭')
  }
}

const clearAllAlerts = () => {
  alerts.value.forEach(alert => alert.dismissed = true)
  message.success('所有告警已清空')
}

const viewAlertDetails = (alert: any) => {
  notification.info({
    message: alert.message,
    description: alert.description,
    duration: 0,
  })
}

const markNotificationRead = (notificationId: number) => {
  const notification = notifications.value.find(n => n.id === notificationId)
  if (notification) {
    notification.read = true
  }
}

const markAllNotificationsRead = () => {
  notifications.value.forEach(n => n.read = true)
  message.success('所有通知已标记为已读')
}

// 数据导出方法
const handleExportMenuClick = ({ key }: { key: string }) => {
  switch (key) {
    case 'pdf':
      generatePDFReport()
      break
    case 'excel':
      exportToExcel()
      break
    case 'json':
      exportViaAPI()
      break
  }
}

const exportToExcel = async () => {
  exportLoading.value.excel = true
  try {
    // 模拟导出过程
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 添加到导出历史
    exportHistory.value.unshift({
      id: Date.now(),
      type: 'Excel',
      name: `监控数据_${new Date().toISOString().split('T')[0]}.xlsx`,
      status: '完成',
      timestamp: new Date(),
    })
    
    message.success('Excel文件导出成功')
  } catch (error) {
    message.error('Excel导出失败')
  } finally {
    exportLoading.value.excel = false
  }
}

const generatePDFReport = async () => {
  exportLoading.value.pdf = true
  try {
    // 模拟报告生成过程
    await new Promise(resolve => setTimeout(resolve, 3000))
    
    // 添加到导出历史
    exportHistory.value.unshift({
      id: Date.now(),
      type: 'PDF',
      name: `${reportTemplate.value}报告_${new Date().toISOString().split('T')[0]}.pdf`,
      status: '完成',
      timestamp: new Date(),
    })
    
    message.success('PDF报告生成成功')
  } catch (error) {
    message.error('PDF报告生成失败')
  } finally {
    exportLoading.value.pdf = false
  }
}

const exportViaAPI = async () => {
  exportLoading.value.api = true
  try {
    // 模拟API导出过程
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 添加到导出历史
    exportHistory.value.unshift({
      id: Date.now(),
      type: 'API',
      name: `api_export_${new Date().toISOString().split('T')[0]}.${apiFormat.value}`,
      status: '完成',
      timestamp: new Date(),
    })
    
    message.success('API数据导出成功')
  } catch (error) {
    message.error('API导出失败')
  } finally {
    exportLoading.value.api = false
  }
}

const copyApiUrl = () => {
  const url = `${window.location.origin}/api/monitoring/export?format=${apiFormat.value}`
  navigator.clipboard.writeText(url)
  message.success('API地址已复制到剪贴板')
}

const onDateRangeChange = (dates: [Dayjs, Dayjs] | null) => {
  if (dates) {
    // 处理日期范围变化
    message.info('图表数据已更新')
  }
}

const downloadExportFile = (record: unknown) => {
  // 模拟文件下载
  message.success(`开始下载 ${record.name}`)
}

const deleteExportRecord = (recordId: number) => {
  const index = exportHistory.value.findIndex(record => record.id === recordId)
  if (index > -1) {
    exportHistory.value.splice(index, 1)
    message.success('导出记录已删除')
  }
}

// WebSocket 实时数据处理
const setupWebSocket = () => {
  // 连接WebSocket
  wsStore.connect()
  
  // 订阅系统指标更新
  wsStore.subscribe('system_metrics', (data) => {
    systemMetrics.value = { ...systemMetrics.value, ...data }
  })
  
  // 订阅生命体指标更新
  wsStore.subscribe('life_entity_metrics', (data) => {
    lifeEntityMetrics.value = { ...lifeEntityMetrics.value, ...data }
  })
  
  // 订阅活动更新
  wsStore.subscribe('activity_update', (data) => {
    recentActivities.value.unshift({
      ...data,
      id: Date.now(),
      timestamp: new Date(),
    })
    // 保持最新的20条记录
    if (recentActivities.value.length > 20) {
      recentActivities.value = recentActivities.value.slice(0, 20)
    }
  })
  
  // 订阅告警
  wsStore.subscribe('alert', (data) => {
    alerts.value.unshift({
      ...data,
      id: Date.now(),
      timestamp: new Date(),
    })
    
    // 显示通知
    notification[data.level]({
      message: data.message,
      description: data.description,
      duration: data.level === 'error' ? 0 : 4.5,
    })
  })
  
  // 订阅通知
  wsStore.subscribe('notification', (data) => {
    notifications.value.unshift({
      ...data,
      id: Date.now(),
      timestamp: new Date(),
      read: false,
    })
  })
  
  // 订阅健康状态变化
  wsStore.subscribe('health_change', (data) => {
    recentHealthChanges.value.unshift({
      ...data,
      id: Date.now(),
      timestamp: new Date(),
    })
    // 保持最新的10条记录
    if (recentHealthChanges.value.length > 10) {
      recentHealthChanges.value = recentHealthChanges.value.slice(0, 10)
    }
  })
}

// 生命周期
onMounted(() => {
  // 初始化WebSocket
  setupWebSocket()
  
  // 开启自动刷新
  if (autoRefresh.value) {
    toggleAutoRefresh(true)
  }
})

onUnmounted(() => {
  // 清理定时器
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
  }
  
  // 断开WebSocket连接
  wsStore.disconnect()
})
</script>

<style scoped>
.monitoring-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-content h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.header-content p {
  margin: 0;
  color: #666;
}

.chart-placeholder {
  height: 100%;
  background: linear-gradient(45deg, #f0f2f5, #e6f7ff);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.activity-item {
  padding: 8px 0;
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.activity-entity {
  font-weight: 500;
  color: #262626;
}

.activity-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 4px;
}

.activity-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.activity-time {
  color: #999;
}

.health-distribution {
  margin-bottom: 16px;
}

.health-stat-item {
  text-align: center;
  padding: 16px 8px;
  border-radius: 8px;
  background: #fafafa;
  margin-bottom: 8px;
}

.health-stat-value {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 4px;
}

.health-stat-value.excellent {
  color: #52c41a;
}

.health-stat-value.good {
  color: #1890ff;
}

.health-stat-value.warning {
  color: #faad14;
}

.health-stat-value.critical {
  color: #ff4d4f;
}

.health-stat-label {
  font-size: 12px;
}

.recent-health-changes h4 {
  margin-bottom: 12px;
  font-size: 14px;
  color: #262626;
}

.alerts-container {
  max-height: 400px;
  overflow-y: auto;
}

.empty-alerts {
  text-align: center;
  padding: 40px 0;
}

.unread-notification {
  background-color: #f6ffed;
  border-left: 3px solid #52c41a;
}

.export-section {
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  height: 100%;
}

.export-section h4 {
  margin-bottom: 8px;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.export-section p {
  color: #666;
  font-size: 14px;
  margin-bottom: 16px;
}

.export-history h4 {
  margin-bottom: 16px;
  font-size: 16px;
  color: #262626;
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
  }

  .header-actions {
    margin-top: 16px;
  }

  .activity-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .activity-meta {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
